package com.tzxs.pay.main;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityContentBinding;
import com.tzxs.pay.main.activity.ActivityFragment;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.BillsFragment;
import com.tzxs.pay.main.first.FirstFragment;
import com.tzxs.pay.main.gt.GtInterface;
import com.tzxs.pay.main.gt.GtService;
import com.tzxs.pay.main.gt.broadcast.GtReceiver;
import com.tzxs.pay.main.mine.LoginOutReceiver;
import com.tzxs.pay.main.mine.MineFragment;
import com.tzxs.pay.main.mine.viewmodel.MineViewModel;
import com.tzxs.pay.main.model.MerchantInfoGetter;
import com.tzxs.pay.util.ApiService;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.websocket.NoticeWebSocket;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;


public class ContentActivity extends BaseActivity<ActivityContentBinding> implements GtInterface, LoginOutReceiver.LoginOutInterface {
    private FirstFragment firstFragment;
    private BillsFragment billFragment;
    private ActivityFragment activityFragment;
    private MineFragment mineFragment;
    private MineViewModel model;
    private GtReceiver receiver;  //接收推送通知广播
    private Class aClass = GtService.class;
    private RxPermissions rxPermissions;
    private LoginOutReceiver loginOutReceiver;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_content;
    }

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorToolbarOne));  //初始化ContentActivity状态栏颜色
        disableShiftMode(dataBinding.navigation);
        model = ViewModelProviders.of(this).get(MineViewModel.class);
        rxPermissions = new RxPermissions(this);
        //注册个性推送
        //进入页面加载首页
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), aClass);
        }
        //初始化广播
        initReceiver();
        webSocket();  //创建websocket连接

        //获取用户信息
        model.getUserInfo(() -> {

        });
        if (savedInstanceState != null) {
            firstFragment = (FirstFragment) getSupportFragmentManager().findFragmentByTag(FirstFragment.class.getSimpleName());
        } else {
            firstFragment = new FirstFragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.content_container, firstFragment, FirstFragment.class.getSimpleName());
            transaction.show(firstFragment).commit();
        }
        MerchantInfoGetter.getMerchantInfo(this);
        //底部导航点击事件
        dataBinding.navigation.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                //首页
                case R.id.navigation_home:
                    showFragment(R.id.navigation_home);
                    StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorToolbarOne));  //设置首页界面的状态栏颜色
                    return true;
                //账单
                case R.id.navigation_bill:
                    showFragment(R.id.navigation_bill);
                    StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorToolbarOne));  //设置账单界面的状态栏颜色
                    return true;
                //活动
                case R.id.navigation_activity:
                    showFragment(R.id.navigation_activity);
                    StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorPrimary));  //设置活动界面的状态栏颜色
                    return true;
                //我的
                case R.id.navigation_mine:
                    showFragment(R.id.navigation_mine);
                    StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorPrimary));  //设置我的界面状态栏颜色
                    return true;
            }
            return false;
        });
    }

    private void initReceiver() {
        //登出广播
        loginOutReceiver = new LoginOutReceiver();
        IntentFilter loginOutfilter = new IntentFilter();
        loginOutfilter.addAction(LoginOutReceiver.loginOur);
        registerReceiver(loginOutReceiver, loginOutfilter);
        //动态注册个推广播
        receiver = new GtReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(GtReceiver.action);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {//销毁广播
            unregisterReceiver(receiver);
            unregisterReceiver(loginOutReceiver);
            loginOutReceiver = null;
            receiver = null;
        }
        //AidlUtil.getInstance().disconnectPrinterService(this);
    }

    //获取权限
    @SuppressLint("CheckResult")
    private void requestPermission() {
        rxPermissions.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        PushManager.getInstance().initialize(this.getApplicationContext(), aClass);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        Toast.makeText(ContentActivity.this, "需要获取手机读写权限！", Toast.LENGTH_SHORT).show();
                    } else {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        startActivity(intent);
                    }
                });
    }

    /**
     * 显示fragment
     *
     * @param id 底部bottomNavigation的item id
     */

    private void showFragment(@IdRes int id) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //在显示fragment之前  隐藏 之前显示的fragment
        hideFragment(transaction);
        switch (id) {
            //首页
            case R.id.navigation_home:

                if (firstFragment == null) {
                    firstFragment = new FirstFragment();
                    transaction.add(R.id.content_container, firstFragment, FirstFragment.class.getSimpleName());
                } else {
                    transaction.show(firstFragment);
                }

                break;
            //账单
            case R.id.navigation_bill:
                if (billFragment == null) {
                    billFragment = new BillsFragment();
                    transaction.add(R.id.content_container, billFragment, BillsFragment.class.getSimpleName());
                } else {
                    transaction.show(billFragment);
                }


                break;
            //活动
            case R.id.navigation_activity:
                if (activityFragment == null) {
                    activityFragment = new ActivityFragment();
                    transaction.add(R.id.content_container, activityFragment, ActivityFragment.class.getSimpleName());
                } else {
                    transaction.show(activityFragment);
                }


                break;
            //我的
            case R.id.navigation_mine:
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    transaction.add(R.id.content_container, mineFragment, MineFragment.class.getSimpleName());
                } else {
                    transaction.show(mineFragment);
                }
                break;

        }
        transaction.commit();

    }

    //隐藏fragment
    private void hideFragment(FragmentTransaction transaction) {
        if (firstFragment != null) {
            transaction.hide(firstFragment);
        }
        if (billFragment != null) {
            transaction.hide(billFragment);
        }
        if (activityFragment != null) {
            transaction.hide(activityFragment);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }

    }


    //去掉bottomNavigationView的动画效果
    @SuppressLint("RestrictedApi")
    public void disableShiftMode(BottomNavigationView view) {
        //获取子View BottomNavigationMenuView的对象
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
        try {
            //设置私有成员变量mShiftingMode可以修改
            Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setBoolean(menuView, false);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                //去除shift效果
                item.setShiftingMode(false);
                item.setChecked(item.getItemData().isChecked());
            }
        } catch (NoSuchFieldException e) {
            Log.e("BNVHelper", "没有mShiftingMode这个成员变量", e);
        } catch (IllegalAccessException e) {
            Log.e("BNVHelper", "无法修改mShiftingMode的值", e);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MerchantInfoGetter.handleResultForMerchantInfo(data,requestCode,resultCode);
    }

    private long first = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long second = System.currentTimeMillis();
            if (second - first < 2000) {//当第二次点击时间小于2s  就退出
                System.exit(0);
            } else {
                Toast.makeText(this, "再次点击退出app!", Toast.LENGTH_SHORT).show();
                first = second;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void updateUi(String content) {
        if (firstFragment != null) {
            firstFragment.updateUi(content);
        }
    }

    @Override
    public void finishActivity() {
        this.finish();
    }


    //进行websocket连接
    private void webSocket() {
        NoticeWebSocket webSocket = null;
        try {
            webSocket = new NoticeWebSocket(new URI("wss://" + ApiService.main + ":8282"), this);
            webSocket.setWeakReference(new WeakReference<>(getApplication()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (webSocket != null) {
            webSocket.connect();
        }
    }
}
